package com.heihei.itextdemo.util;

import com.heihei.itextdemo.dto.TableQueryParamDTO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 通用工具类
 * 
 */
public class CommonUtil {

	public static String getServerIp() {
		try {
			Enumeration<NetworkInterface> IFaces = NetworkInterface.getNetworkInterfaces();
			while (IFaces.hasMoreElements()) {
				NetworkInterface fInterface = IFaces.nextElement();
				if (!fInterface.isVirtual() && !fInterface.isLoopback() && fInterface.isUp()) {
					Enumeration<InetAddress> adds = fInterface.getInetAddresses();
					while (adds.hasMoreElements()) {
						InetAddress address = adds.nextElement();
						byte[] bs = address.getAddress();
						if (bs.length == 4) {
                            return address.getHostName() + "@" + address.getHostAddress();
                        }
					}
				}
			}
			return "";
		} catch (Exception e) {
			return "";
		}

	}


	public static String handleIdStr(String ids) {
		if (StringUtils.isEmpty(ids)) {
			return ids;
		}
		StringBuilder sb = new StringBuilder();
		sb.append("'");
		ids = ids.replaceAll(",", "\',\'");
		sb.append(ids);
		sb.append("'");
		return sb.toString();
	}

	/**
	 * 
	 * 方法描述  生成uuid
	 */
	public static String genUUID() {
		String uuid = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
		return uuid;
	}

	/**
	 * 
	 * 方法描述 返回json数据
	 */
	public static void returnJson(HttpServletResponse response, String json) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * 方法描述  根据角色id获取角色文本
	 */
	public static String getRoleTextByRoleId(Long roleId, Map<Long, String> roleNameData) {
		return Objects.toString(roleNameData.get(roleId), "");
	}

	/**
	 * 
	 * 方法描述  根据角色idList获取角色文本字符串，以,分割
	 */
	public static String getRoleTextByRoleIdList(List<Long> roleIdList, Map<Long, String> roleNameData) {
		if (CollectionUtils.isEmpty(roleIdList)) {
			return "";
		}
		List<String> textList = new ArrayList<String>();
		for (Long roleId : roleIdList) {
			String text = getRoleTextByRoleId(roleId, roleNameData);
			if (StringUtils.isNotEmpty(text)) {
				textList.add(text);
			}
		}
		return StringUtils.join(textList, ",");
	}

	/**
	 * 
	 * 方法描述 根据角色Key获取角色文本
	 */
	public static String getRoleTextByRoleKey(String roleKey, Map<String, String> roleNameData) {
		return Objects.toString(roleNameData.get(roleKey));
	}

	/**
	 * 
	 * 方法描述  根据角色KeyList获取角色文本字符串，以,隔开
	 */
	public static String getRoleTextByRoleKeyList(List<String> roleKeyList, Map<String, String> roleNameData) {
		if (CollectionUtils.isEmpty(roleKeyList)) {
			return "";
		}
		List<String> textList = new ArrayList<String>();
		for (String roleKey : roleKeyList) {
			String text = getRoleTextByRoleKey(roleKey, roleNameData);
			if (StringUtils.isNotEmpty(text)) {
				textList.add(text);
			}
		}
		return StringUtils.join(textList, ",");
	}

	/**
	 * 
	 * 方法描述  根据查询参数，生成含有orderby的Example对象
	 */
	public static <T> T createOrderedExample(Class<T> clazz, TableQueryParamDTO param) {
		try {
			T t = clazz.newInstance();
			if (StringUtils.isNotEmpty(param.getSortField()) && StringUtils.isNotEmpty(param.getSortField())) {
				Method m = clazz.getDeclaredMethod("setOrderByClause", String.class);
				m.invoke(t, camel2UnderLine(param.getSortField()) + "  " + param.getSortValue().toUpperCase());
			}
			return t;
		} catch (Exception e) {
			return null;
		}
	}


	public static <T> T addTenantCriteria(T t, String tenantId) {
		try {
			Method m = t.getClass().getDeclaredMethod("andTenantIdEqualTo", String.class);
			m.invoke(t, tenantId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return t;
	}

	/**
	 * 
	 * 方法描述 驼峰属性名转换为下划线属性名
	 */
	public static String camel2UnderLine(String camelCaseName) {
		StringBuilder result = new StringBuilder();
		if (camelCaseName != null && camelCaseName.length() > 0) {
			result.append(camelCaseName.substring(0, 1).toLowerCase());
			for (int i = 1; i < camelCaseName.length(); i++) {
				char ch = camelCaseName.charAt(i);
				if (Character.isUpperCase(ch)) {
					result.append("_");
					result.append(Character.toLowerCase(ch));
				} else {
					result.append(ch);
				}
			}
		}
		return result.toString().toUpperCase();
	}

	public static List<Long> str2LongList(String str, String split) {
		List<Long> result = new ArrayList<Long>();
		if (StringUtils.isEmpty(str)) {
			return result;
		}
		for (String s : str.split(split)) {
			result.add(NumberUtils.toLong(s));
		}
		return result;
	}

	public static List<Long> str2LongList(String str) {
		return str2LongList(str, ",");
	}

	public static List<String> str2List(String str, String split) {
		List<String> result = new ArrayList<String>();
		if (StringUtils.isEmpty(str)) {
			return result;
		}
		for (String s : str.split(split)) {
			result.add(s);
		}
		return result;
	}

	public static List<String> str2List(String str) {
		return str2List(str, ",");
	}

	public static List<Integer> str2IntList(String str, String split) {
		List<Integer> result = new ArrayList<Integer>();
		if (StringUtils.isEmpty(str)) {
			return result;
		}
		for (String s : str.split(split)) {
			result.add(NumberUtils.toInt(s));
		}
		return result;
	}

	/**
	 * list转string
	 */
	public static String listToString(List<String> list) {
		String str = "";
		if (CollectionUtils.isNotEmpty(list)) {
			StringBuilder sb = new StringBuilder();
			for (String string : list) {
				sb.append(string + ",");
			}
			if (StringUtils.isNotEmpty(sb.toString())) {
				str = sb.toString().substring(0, sb.toString().length() - 1);
			}
		}
		return str;
	}

	public static List<Integer> str2IntList(String str) {
		return str2IntList(str, ",");
	}

	/**
	 * 生成编号
	 */
	public static String getNumber(int count) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String dateStr = sdf.format(new Date());
		StringBuilder sb = new StringBuilder(dateStr);
		Random rand = new Random();
		for (int i = 0; i < count; i++) {
			sb.append(rand.nextInt(10));
		}
		return sb.toString();
	}

	/**
	 * 获取项目ip端口信息
	 */
	public static String getUrl(HttpServletRequest request) {
		String uri = request.getRequestURI();
		String url = request.getRequestURL().toString();
		String path = url.replace(uri, "");
		return path;
	}

	/**
	 * 判断对象的所有属性是否为空
	 */
	public static boolean entityNotNUll(Object o) {
		try {
			for (Field field : o.getClass().getDeclaredFields()) {
				field.setAccessible(true);// 把私有属性公有化
				if (field.getName().equals("serialVersionUID")) {
					continue;
				}
				Object object = field.get(o);
				if (object instanceof CharSequence) {
					if (StringUtils.isNotBlank((String) object)) {
						return true;
					} else {
						continue;
					}
				} else {
					if (object != null) {
						return true;
					} else {
						continue;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 通过文件名称获取文件格式
	 */
	public static String getFileSuffix(String fileName) {
		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
		return suffix;
	}

	/**
	  * 将实体显示信息转换为前段所需信息
	  */
	// public static JSONObject getEntityShoewInfo(Map<String, String> map,
	// Object o) {
	// JSONObject jsonObject=new JSONObject();
	// try {
	// for (Field field : o.getClass().getDeclaredFields()) {
	// field.setAccessible(true);// 把私有属性公有化
	// if(map.containsKey(field.getName())){
	// jsonObject.put(map.get(field.getName()), field.get(o));
	// }
	//
	// }
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// return jsonObject;
	// }

	// /**
	// * 将对象显示信息转换为前段所需格式
	// */
	// public static List<BaseVO> getEntityShoewList(Map<String,
	// BimTableDictionary> map, Object o) {
	// List<BaseVO> list=new ArrayList<BaseVO>();
	// if(o==null){
	// return list;
	// }
	// try {
	// for (Field field : o.getClass().getDeclaredFields()) {
	// field.setAccessible(true);// 把私有属性公有化
	// if(map.containsKey(field.getName())){
	// BaseVO vo=new BaseVO();
	// vo.setKey(field.getName());
	// vo.setValue(field.get(o));
	// BimTableDictionary dictionary=map.get(field.getName());
	// if(dictionary!=null){
	// vo.setLable(dictionary.getChineseName());
	// vo.setSort(dictionary.getSort());
	// }
	// list.add(vo);
	// }
	// }
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// Collections.sort(list, Comparator.comparing(BaseVO::getSort));
	// return list;
	// }

	/**
	 * 获取静态文件路径
	 */
	public static String getStaticPath(HttpServletRequest request) {
		try {
			File ff = ResourceUtils.getFile("src/main/resources/temp_files/");
			// File ff = ResourceUtils.getFile("classpath:static");
			return ff.getAbsolutePath();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;

	}
	/**
	 * 获取字符串中的数字
	 */
	public static int getIndex(String str) {
		if (StringUtils.isEmpty(str)) {
			return -1;
		}

		String regEx = "[^0-9]";//匹配指定范围内的数字
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);

		String index = m.replaceAll("").trim();

		if (StringUtils.isEmpty(index)) {
			return -1;
		}
		return Integer.parseInt(index);
	}
}
